package com.delicious.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.delicious.dao.BaseDao;
import com.delicious.dao.MessageDao;
import com.delicious.entity.Message;

public class MessageDaoImpl extends BaseDao implements MessageDao {

	public boolean saveMessage(Message msg) {
		int rows = 0;
		String sql ="INSERT INTO messages(username,phone,email,content,publishDate,isread) VALUES(?,?,?,?,?,1)";
		ArrayList list = new ArrayList();
		list.add(msg.getUsername());
		list.add(msg.getPhone());
		list.add(msg.getEmail());
		list.add(msg.getContent());
		list.add(msg.getPublishDate());
		openConnection();
		
		try {
			rows = executeUpdate(sql, list.toArray());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeConnection();
		}
		return rows>0;
	}

	public List<Message> getMessageList(int pageNum,int pageSize) {
		List<Message> list = new ArrayList<Message>();
		String sql = "select * from messages ";
		openConnection();
		ResultSet rs = null;
		ArrayList word = new ArrayList();
		if(pageNum > 0 && pageSize >0){
			sql += "limit ?,?";
			word.add((pageNum-1)*pageSize);
			word.add(pageSize);
		}
		
		try {
			rs = executeQuery(sql, word.toArray());
			while(rs.next()){
				int id = rs.getInt("id");
				String username = rs.getString("username");
				String phone = rs.getString("phone");
				String email = rs.getString("email");
				String content = rs.getString("content");
				String publishDate = rs.getString("publishDate");
				int isRead = rs.getInt("isRead");
				Message m = new Message(id, username, phone, email, content, publishDate, isRead);
				list.add(m);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeConnection();
		}
		
		return list;
	}

}
